from PyQt5.QtCore import QThread, pyqtSignal
from socket import *
import time


class SearchDeviceThread(QThread):
    _signal = pyqtSignal(str)

    def __init__(self):
        super(SearchDeviceThread, self).__init__()

    def run(self):
        print('start search')
        start_time = int(time.time())
        udp_socket = socket(AF_INET, SOCK_DGRAM)
        udp_socket.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
        con = True
        while con:
            udp_socket.sendto('get_info'.encode(), ('255.255.255.255', 6666))
            data, addr = udp_socket.recvfrom(1024)
            self._signal.emit(addr[0])
            print(str(int(time.time()) - start_time))
            if int(time.time()) - start_time >= 10:
                con = False
                print('搜索完成')

    def connect(self, func):
        self._signal.connect(func)
